package com.example.wac.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.wac.constant.Constant;
import com.example.wac.enums.ErrorCode;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


/**
 * @author wuancheng
 * @description Jwt工具类
 * @date 2021-07-13 11:06:00
 */

public class JwtUtil {
    /**
     * 过期时间60分钟
     */
    private static final long EXPIRE_TIME = 60 * 60 * 1000;
    /**
     * jwt 密钥
     */
    private static final String SECRET = "jwt_secret";

    /**
     * 生成签名，30分钟后过期
     * @param userId
     * @return
     */
    public static String createJWT(String userId) {
        try {
            //确定过期时间
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            //生成秘钥
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            return JWT.create()
                    // 将 user id 保存到 token 里面
                    .withAudience(userId)
                    // 填充token过期时间
                    .withExpiresAt(date)
                    // token 的密钥
                    .sign(algorithm);
        } catch (Exception e) {
            throw ErrorCode.TOKEN_ERROR.getAppException();
        }
    }

    /**
     * 根据token获取userId
     * @param token
     * @return
     */
    public static String getUserId(String token) {
        try {
            //解密后获取负载信息（集合）中存入的userID
            String userId = JWT.decode(token).getAudience().get(0);
            return userId;
        } catch (JWTDecodeException e) {
            throw ErrorCode.TOKEN_ERROR.getAppException();
        }
    }

    /**
     * 校验token
     * @param token
     * @return
     */
    public static boolean checkSign(HttpServletRequest request, String token) {
        try {
            //生成密钥
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            //验证密钥
            JWTVerifier verifier = JWT.require(algorithm)
                    .build();
            DecodedJWT jwt = verifier.verify(token);
            if (jwt != null){
                request.setAttribute(Constant.CURRENT_USER,getUserId(token));
                return true;
            }else {
                return false;
            }
        } catch (JWTVerificationException exception) {
            throw ErrorCode.TOKEN_ERROR.getAppException();
        }
    }

    /**
     * 刷新token
     * @param token
     * @return
     */
    public static String freshSign(String token){
        String userId = getUserId(token);
        String sign = createJWT(userId);
        return sign;
    }
}
